﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aij1.Model;
using DevExpress.Xpo;
using DevExpress.Data.Filtering;
using System.Data;
using Aij1.Utils;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Collections;
using System.Web;

namespace Aij1.BLL
{
    public class ArticleData
    {
        public static A_Article CreateNewArticle(Session session)
        {
            S_Person user = AuthData.GetCurrentUser(session);
            A_Article art = new A_Article(session)
            {
                DisplayTime = DateTime.Now,
                EditorId = user,
                Author = user == null ? "" : user.TrueName,
                Status = ArticleStatusType.审核通过,
            };
            return art;
        }

        public static SortProperty[] GetDefaultSort()
        {
            return new SortProperty[]{
                new SortProperty("SetTopTime", DevExpress.Xpo.DB.SortingDirection.Descending),
                new SortProperty("DisplayTime", DevExpress.Xpo.DB.SortingDirection.Descending),
            };
        }

        public static CriteriaOperator GetDefaultFilter()
        {
            return CriteriaOperator.Parse("Status=?", (int)ArticleStatusType.审核通过);
        }

        public static A_Article GetNextNews(A_Article art, ArticleType aType)
        {
            XPCollection<A_Article> arts = new XPCollection<A_Article>(art.Session,
                CriteriaOperator.Parse("Oid<? AND CategoryId=? AND AType=?", art.Oid, art.CategoryId, (int)aType)
                * GetDefaultFilter(),
                new SortProperty("Oid", DevExpress.Xpo.DB.SortingDirection.Descending));
            arts.TopReturnedObjects = 1;
            return arts.Count == 0 ? null : arts[0];
        }

        public static A_Article GetPrevNews(A_Article art, ArticleType aType)
        {
            XPCollection<A_Article> arts = new XPCollection<A_Article>(art.Session,
                CriteriaOperator.Parse("Oid>? AND CategoryId=? AND AType=?", art.Oid, art.CategoryId, (int)aType)
                * GetDefaultFilter(),
                new SortProperty("Oid", DevExpress.Xpo.DB.SortingDirection.Ascending));
            arts.TopReturnedObjects = 1;
            return arts.Count == 0 ? null : arts[0];
        }

        public static IDataReader GetPagedNewsList(DbPager pager)
        {
            return DBHelper.DefaultHelper.ExecPageReader(pager);
        }

        public static IDataReader GetPagedNewsList(Session session, DbPager pager, string keyword)
        {
            A_Keyword key = KeywordData.GetMainKeyword(session, keyword);
            return DBHelper.DefaultHelper.ExecPageReader(pager, DBHelper.Comm.CreateParameter("Keyword", "%" + keyword + "%"),
                DBHelper.Comm.CreateParameter("Key", key == null ? keyword : key.Title));
        }

        public static XPCollection<A_Article> GetTopNews(Session session, string catIds, int topN)
        {
            XPCollection<A_Article> arts = new XPCollection<A_Article>(session,
                CriteriaOperator.Parse(String.Format("CategoryId IN ({0})", catIds))
                * GetDefaultFilter());
            arts.Sorting.AddRange(GetDefaultSort());

            arts.TopReturnedObjects = topN;
            return arts;
        }

        public static void SetTop(Session session, string ids)
        {
            string sql = String.Format("UPDATE A_Article SET SetTopTime='{0}' WHERE Oid IN ({1})", DateTime.Now, ids);
            session.ExecuteNonQuery(sql);
        }

        public static void UnsetTop(Session session, string ids)
        {
            string sql = String.Format("UPDATE A_Article SET SetTopTime=NULL WHERE Oid IN ({0})", ids);
            session.ExecuteNonQuery(sql);
        }

        public static void Delete(Session session, string ids)
        {
            XPCollection<A_Article> arts = new XPCollection<A_Article>(session, CriteriaOperator.Parse(String.Format("OID IN ({0})", ids)));
            foreach (var art in arts.ToArray())
            {
                art.Delete();
            }
        }

        /// <summary>
        /// 从文章中提取关键词
        /// </summary>
        /// <param name="art"></param>
        /// <returns></returns>
        public static string PickKeyword(A_Article art)
        {
            IList<A_Keyword> keywords = KeywordData.GetAllInUseKeywords(art.Session);
            string total = art.Title + "\t\r\n" + art.Intro + "\t\r\n" + CommOp.RemoveHTML(art.Content) + String.Join("\t\r\n", art.Photos.Select(p => p.Title + "\t\r\n" + p.Intro).ToArray());
            total = total.ToUpper();
            var aks = keywords.Where(key => total.Contains(key.Title.ToUpper())).ToList();
            foreach (var ak in aks.ToArray())
            {
                if (ak.ParentId != null) aks.Add(ak.ParentId);
            }
            var distAk = aks.Where(ak => ak.ParentId == null).Distinct();
            string[] articleKeys = distAk.Select(k => k.Title).ToArray();
            return string.Join(";", articleKeys);
        }

        /// <summary>
        /// 保存文章中图片信息到数据库
        /// </summary>
        /// <param name="page"></param>
        /// <param name="A"></param>
        /// <param name="saveToServer"></param>
        public static void SaveImage(A_Article A, bool saveToServer)
        {
            Page page = HttpContext.Current.Handler as Page;
            Regex re = new Regex("<img\\s+([^>]*)[/]?>", RegexOptions.IgnoreCase);
            //Regex re = new Regex("<img\\s+[^>]*?src=[\'\"](?<url>http://[^\'\"]+)[\'\"]\\s*[^>]+>", RegexOptions.IgnoreCase);
            //Regex re = new Regex("<img\\s+[^>]*alt=[\'\"](?<alt>[^\'\"]+)?[\'\"][^>]*src=[\'\"](?<url>http://[^\'\"]+)[\'\"][^>]*>", RegexOptions.IgnoreCase);
            MatchCollection mc = re.Matches(A.Content);
            IList<string> imgUrls = new List<String>();

            string sampleUrl = A.SamplePhotoId == null ? "" : A.SamplePhotoId.Url;
            foreach (A_Photo photo in A.Photos.ToArray())
            {
                photo.Delete();
            }
            A.SamplePhotoId = null;

            foreach (Match m in mc)
            {
                string imgAttr = m.Groups[1].Value.Replace('\'', '"');
                DictProp dp = new DictProp(imgAttr, " ", "=");
                string url = dp.GetPropStr("src").Replace("\"", "");
                string alt = dp.GetPropStr("alt").Replace("\"", "");
                //string alt = m.Groups["alt"].Value;
                A_Photo photo = new A_Photo(A.Session)
                {
                    AlbumId = A,
                    Url = url,
                    Title = alt,
                };

                if (saveToServer)
                {
                    AlbumData.SaveToLocal(photo);
                    A.Content = A.Content.Replace(url, page.ResolveUrl(photo.Url));
                }
                else
                {
                    AlbumData.ReCalcPhoto(photo);
                }
            }

            foreach (var photo in A.Photos)
            {
                if (A.SamplePhotoId == null || sampleUrl == photo.Url)
                {
                    A.SamplePhotoId = photo;
                }
            }
        }
    }
}
